<template>
    <div class="add-first-box">
        <el-button type="success" size="small" title="新增权限组" @click="editAuthority('add')">
            <el-icon size="18"><DocumentAdd /></el-icon>
        </el-button>
        <el-button type="primary" size="small" @click="reSearch">查询</el-button>
    </div>
    <div class="second-box">
        <div class="authirity-box" v-for="(item) in authoritysInfo" :key="item.ID">
            <div class="title-box">{{ item.AUTHORITYNAME }}</div>
            <div class="icon-box">
                <el-button type="warning" size="small" title="编辑权限" @click="editAuthority('selectChange',item)">
                    <el-icon size="18"><BrushFilled /></el-icon>
                </el-button>
                <el-button type="primary" size="small" title="编辑" @click="editAuthority('update',item)">
                    <el-icon size="18"><Edit /></el-icon>
                </el-button>
                <el-button type="danger" size="small" title="删除" @click="editSubmit('delete',item)">
                    <el-icon size="18"><RemoveFilled /></el-icon>
                </el-button>
            </div>            
        </div>
    </div>
    <Drawer ref="drawerRef" :title="title" :size="size"
        @cancel-submit="resetForm"
        @submit="editSubmit(submitType,submitData)"
    >
        <el-form :model="authoritysObj" ref="updateFormRef" :rules="rules" 
            v-if="(submitType !== 'selectChange' && submitType !== 'treeNode')">
            <el-form-item label="ID" :label-width="formLabelWidth">
                <el-input v-model="authoritysObj.ID" autocomplete="off" disabled />
            </el-form-item>
            <el-form-item label="权限组" :label-width="formLabelWidth" prop="AUTHORITYNAME">
                <el-input v-model="authoritysObj.AUTHORITYNAME" autocomplete="off"/>
            </el-form-item>
            <el-form-item label="备注" :label-width="formLabelWidth" >
                <el-input v-model="authoritysObj.REMARK" autocomplete="off" />
            </el-form-item>
        </el-form>
        <DirsOfAuthority v-for="(item,i) in dirsInfo" :key="i" :item="item" :oldDirsInfo="dirsInfo"
            v-if="submitType === 'selectChange'" class="sub-dirs-box"
        />
    </Drawer>
</template>

<script setup>
import { ref,reactive } from 'vue'
import {getAuthoritysInfo , editAuthorityInfo ,changeAuthority} from '@/utils/adminApi/authority'
import Drawer from '@/components/Drawer.vue'
import {mainStore} from '@/stores/store'
import { getDirsAndMidInfo } from '@/utils/adminApi/authority'
import { recursion } from '@/utils/recursion'
import {msgOpen} from '@/utils/msg'
import { confirm } from '@/utils/confirm'
import DirsOfAuthority from '@/components/DirsOfAuthority.vue'

let useStore = mainStore()

let authoritysInfo = ref([])
let authoritysObj = reactive({
    ID:null,
    AUTHORTIYNAME:"",
    REMARK:""
})

let drawerRef = ref(null)
let title = ref("")
let size = ref("45%")
let formLabelWidth = ref("80")
let submitType = ref('')
let dirsInfo = ref([])
let submitData = reactive({}) //权限编辑后提交对象

//表单验证ref
let updateFormRef = ref(null)
//输入框验证规则
let rules = reactive({
    AUTHORITYNAME: [
        { required: true, message: '请输入权限组名称', trigger: 'blur' },
    ]
})

//重新查询
const reSearch = async ()=>{
    let authoritysInfoRes = await getAuthoritysInfo()
    // console.log(authoritysInfoRes);    
    authoritysInfo.value = authoritysInfoRes.datas.authoritys
}

//重置权限组对象
const resetForm = ()=>{
    authoritysObj = reactive({
        ID:null,
        AUTHORTIYNAME:"",
        REMARK:""
    })
    useStore.clearNeedAddAndNeedDelAuthDirsMidd()
}


/**
 * 编辑权限组
 * @param type 处理类型
 * @param row  行对象
 */
const editAuthority = async (type,row)=>{
    // console.log(type);
    // console.log(row);       
    submitType.value = type
    drawerRef.value.open()
    if(type === "add"){
        title.value = "新增"
        resetForm()
        submitData = authoritysObj
    }else if(type === "update"){
        title.value = "编辑"
        authoritysObj = row
        submitData = authoritysObj
    }else if(type === "selectChange" ){
        title.value = "编辑权限明细"
        //重新编辑权限组时，先重置权限组对象
        dirsInfo.value = []
        let dirsRes = await getDirsAndMidInfo(row.ID)
        //存入旧权限
        useStore.setOldAuthDirsMidd(dirsRes.resDatas.dirsAndMid)
        //转换为树形结构        
        dirsInfo.value = recursion(dirsRes.resDatas.dirsAndMid)

        //先为空，再重新获取
        submitData = reactive({
            authorityId:row.ID,
            needAdd:[],
            needDel:[],
            needUpdate:[]
        })           
    }
}

/**
 * 权限处理
 * 新增，编辑，删除，变更权限
 * @param {String} type 处理类型
 * @param {Object} data 表单对象,selectChange改变权限时对象属性为数组
 */
const editSubmit = async (type,data)=>{
    if(type === 'update' || type === 'add'){
        updateFormRef.value.validate(async (valid)=>{
            if(!valid){
                return false
            }else{         
                drawerRef.value.showLoading()
                let newAuthoritys = await editAuthorityInfo(type,data)
                // console.log(newAuthoritys);
                drawerRef.value.hideLoading()
                drawerRef.value.close()
                msgOpen(newAuthoritys.msg,'success') 
                reSearch()
            }
        })
    }else if(type === "delete"){
        let res = await confirm(data.ID)       
        if(res){
            let newAuthoritys = await editAuthorityInfo(type,data)
            // console.log(newAuthoritys);
            msgOpen(newAuthoritys.msg,'success')
            reSearch()
        }
    }else if(type === "selectChange"){
        drawerRef.value.showLoading()
        if(useStore.needAddAuthDirsMidd.length){
            data.needAdd = handingData("add",useStore.needAddAuthDirsMidd,data.authorityId).addDataArr
        }else{
            data.needAdd = []
        }
        if(useStore.needDelAuthDirsMidd.length){
            data.needDel = handingData("del",useStore.needDelAuthDirsMidd,data.authorityId).delDataArr 
        }else{
            data.needDel = []
        }
        if(useStore.needUpdateAuthDirsMidd.length){
            data.needUpdate = handingData("update",useStore.needUpdateAuthDirsMidd,data.authorityId).updateDataArr 
        }else{
            data.needUpdate = []
        }
        // console.log(data)
        if(!data.needAdd.length && !data.needDel.length && !data.needUpdate.length){
            msgOpen("未变更权限，无需提交")
            drawerRef.value.hideLoading()
        }else{
            let newAuthoritys = await changeAuthority(type,data)
            // console.log(newAuthoritys)
            drawerRef.value.hideLoading()
            drawerRef.value.close()
            msgOpen(newAuthoritys.msg,'success')
            reSearch()
            //重新编辑权限组时，先重置权限组对象
            dirsInfo.value = []
            //重新获取权限，获取前须先清空旧权限
            useStore.clearOldAuthDirsMidd()
            let dirsRes = await getDirsAndMidInfo(data.authorityId)
            //存入旧权限
            useStore.setOldAuthDirsMidd(dirsRes.resDatas.dirsAndMid)
            //转换为树形结构        
            dirsInfo.value = recursion(dirsRes.resDatas.dirsAndMid)
        }     
    }
}

/**
 * 权限变更前数据处理
 * @param type 处理类型
 * @param data 处理数据
 * @param authorityId 
 */
const handingData = (type,data,authorityId)=>{
    let addArr = []
    let addDataArr = []
    let delArr = []
    let delDataArr = []
    let updateArr = []
    let updateDataArr = []
    if(type === "add"){
        data.forEach((item) => {
            let obj = {
                authorityId:authorityId,
                dirId:item.ID,
                isAdd:item.IS_ADD,
                isUpdate:item.IS_UPDATE,
                isDel:item.IS_DEL
            }
            addArr.push(obj)
        })
        // console.log(addArr)
        addArr.forEach((item) => {
            let itemArr = Object.values(item)
            addDataArr.push(itemArr)
        })
    }
    if(type === "del"){
        data.forEach((item) => {
            let obj = {
                admId:item.ADMID,
            }
            delArr.push(obj)
        }) 
        // console.log(delArr)
        delArr.forEach((item) => {
            let itemArr = Object.values(item)
            delDataArr.push(itemArr)
        })
    }
    if(type === "update"){
        data.forEach((item) => {
            let obj = {                
                isAdd:item.IS_ADD,
                isUpdate:item.IS_UPDATE,
                isDel:item.IS_DEL,
                admId:item.ADMID,
            }
            updateArr.push(obj)
        }) 
        // console.log(updateArr)
        updateArr.forEach((item) => {
            let itemArr = Object.values(item)
            updateDataArr.push(itemArr)
        })
    }    
    return {
        addDataArr,
        delDataArr,
        updateDataArr        
    }
}


</script>

<style lang="less" scoped>
.add-first-box {
    height: 5%;
    width: 100%;
    border-bottom: #467df5 .0625rem solid;
    padding-left: 1.25rem;
    display: flex;
    justify-content: start;
    align-items: center;
}
.second-box{
    height: 95%;
    width: 100%;
    .authirity-box{
        height: 2.5rem;
        width: 50%;
        display: flex;
        align-items: center;
        .title-box{
            width: 70%;
            font-size: .875rem;
            color: #5e6166;
            padding-left: 1.25rem;
        }
        .icon-box{
            width: 30%;
            display: flex;
            align-items: center;
        }
    }
    .authirity-box:hover{
        background-color: rgba(238, 239, 241, 0.5);
    }
} 

.custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
    .title-span-box{
        width: 100%;
        flex: 1;
        display: flex;
        align-items: center;
        .icon-title-box{
            width: 50%;
            span{
                margin-left: .625rem;
            }
        }
        .contorl-btn-box{
            width: 50%;
            display: flex;
            align-items: center; 
        }
        
    }
}


</style>